<!-- src/views/Message.vue -->
<template>
  <div class="message-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>消息中心</span>
          <el-button type="primary" @click="showSendDialog = true">
            <i class="fas fa-paper-plane"></i> 发送新消息
          </el-button>
        </div>
      </template>

      <!-- 消息列表 -->
      <el-table :data="messageList" style="width: 100%">
        <el-table-column prop="subject" label="主题" width="200" />
        <el-table-column prop="recipient" label="收件人" width="180">
          <template #default="scope">
            {{ scope.row.recipient || '1934273972@qq.com' }}
          </template>
        </el-table-column>
        <el-table-column prop="sendTime" label="发送时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.sendTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="reade" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.reade ? 'success' : 'warning'">
              {{ scope.row.reade ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
                size="small"
                @click="viewMessageDetail(scope.row.id)"
            >查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 发送消息对话框 -->
    <el-dialog v-model="showSendDialog" title="发送新消息">
      <el-form :model="newMessage" label-width="80px">
        <el-form-item label="主题">
          <el-input v-model="newMessage.subject" placeholder="请输入消息主题" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input
              v-model="newMessage.content"
              type="textarea"
              :rows="5"
              placeholder="请输入消息内容"
          />
        </el-form-item>
        <el-form-item label="紧急">
          <el-switch v-model="newMessage.urgent" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSendDialog = false">取消</el-button>
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 消息详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="消息详情">
      <div v-if="currentMessage">
        <div class="message-header">
          <h3>{{ currentMessage.subject }}</h3>
          <div class="message-meta">
            <span>发送至: {{ currentMessage.recipient || '1934273972@qq.com' }}</span>
            <span>时间: {{ formatDateTime(currentMessage.sendTime) }}</span>
            <el-tag :type="currentMessage.urgent ? 'danger' : 'info'">
              {{ currentMessage.urgent ? '紧急' : '普通' }}
            </el-tag>
          </div>
        </div>
        <div class="message-content">
          <p>{{ currentMessage.content }}</p>
        </div>
        <div class="message-status">
          <el-tag :type="currentMessage.reade ? 'success' : 'warning'">
            状态: {{ currentMessage.reade ? '已读' : '未读' }}
          </el-tag>
          <el-tag :type="currentMessage.successe ? 'success' : 'danger'">
            发送: {{ currentMessage.successe ? '成功' : '失败' }}
          </el-tag>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import messageApi from '@/api/message.js'

// 当前登录用户信息
const currentUser = {
  name: sessionStorage.getItem('uname') || '未知用户',
  email: sessionStorage.getItem('uemail') || 'user@example.com'
}

// 消息列表数据
const messageList = ref([])
// 是否显示发送对话框
const showSendDialog = ref(false)
// 是否显示详情对话框
const showDetailDialog = ref(false)
// 当前查看的消息详情
const currentMessage = ref(null)

// 新消息对象
const newMessage = ref({
  subject: '',
  content: '',
  urgent: false
})

// 加载消息列表
const loadMessages = async () => {
  try {

    const response = await messageApi.getMessagesBySender(currentUser.name)
    messageList.value = response.data || []


    const mockMessages = [
      {
        id: 1,
        senderId: 1,
        senderName: currentUser.name,
        recipient: '1934273972@qq.com',
        subject: 'zs1',
        content: 'pp1',
        urgent: true,
        sendTime: new Date().toISOString(),
        reade: false,
        successe: true
      },
      {
        id: 2,
        senderId: 1,
        senderName: currentUser.name,
        recipient: '1934273972@qq.com',
        subject: 'z2',
        content: 'll',
        urgent: false,
        sendTime: new Date().toISOString(),
        reade: true,
        successe: true
      },
      {
        id: 3,
        senderId: 1,
        senderName: currentUser.name,
        recipient: '1934273972@qq.com',
        subject: 'z3',
        content: 'll',
        urgent: true,
        sendTime: new Date().toISOString(),
        reade: false,
        successe: false
      }
    ];

    messageList.value = mockMessages;
    ElMessage.success('消息列表加载成功');
  } catch (error) {
    ElMessage.error('加载消息列表失败: ' + error.message);
  }
}

// 发送消息
const sendMessage = async () => {
  try {
    const messageData = {
      ...newMessage.value,
      senderName: currentUser.name,
      recipient: '1934273972@qq.com' // 固定收件人
    }

    await messageApi.sendMessage(messageData)
    ElMessage.success('消息发送成功')
    showSendDialog.value = false
    newMessage.value = { subject: '', content: '', urgent: false }

    // 刷新消息列表
    await loadMessages()
  } catch (error) {
    ElMessage.error('消息发送失败: ' + error.message)
  }
}

// 查看消息详情
const viewMessageDetail = async (messageId) => {
  try {
    const response = await messageApi.getMessageDetail(messageId)
    currentMessage.value = response.data
    showDetailDialog.value = true
  } catch (error) {
    ElMessage.error('获取消息详情失败: ' + error.message)
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''

  // 如果是字符串格式的日期
  if (typeof dateTime === 'string') {
    return new Date(dateTime).toLocaleString()
  }

  // 如果是LocalDateTime对象
  return `${dateTime.year}-${padZero(dateTime.monthValue)}-${padZero(dateTime.dayOfMonth)}
          ${padZero(dateTime.hour)}:${padZero(dateTime.minute)}:${padZero(dateTime.second)}`
}

// 补零函数
const padZero = (num) => {
  return num.toString().padStart(2, '0')
}

// 组件挂载时加载消息
onMounted(() => {
  loadMessages()
})
</script>

<style scoped>
.message-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-header {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.message-header h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
}

.message-meta {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 14px;
}

.message-content {
  line-height: 1.8;
  min-height: 200px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.message-status {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}
</style>